//
//  SRHomewokPictureViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/9/11.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRHomewokPictureViewController.h"

#import <MJRefresh/MJRefresh.h>
#import "SRHomeworkPictureModel.h"
//#import "SRHomeworkPictureTableViewCell.h"
#import "SRHomeworkPictureCollectionViewCell.h"

#import "SRHomeworkPictureCollectionHeaderView.h"
#import "SRSchoolClassServices.h"
#import "SRHomeworkAnswerModel.h"
#import "SRHomeworkDetailItemModel.h"

#import "FZMCCacheManager.h"
#import "SRAudioPlayerManager.h"
#import "UIButton+FZGreenButton.h"
#import <NSString+Size.h>

//#import "AudioRecord.h"
//#import <SRUploadQiniuManager.h>
//#import <lame/lame.h>

@interface SRHomewokPictureViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionView          *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSMutableArray            *items;

@property (strong, nonatomic) SRHomeworkPictureCollectionHeaderView *headerView;
@property (strong, nonatomic) UIButton *nextButton;

@property (strong, nonatomic) UIView *bottomView;
@property (strong, nonatomic) UIButton *previousButton;

@property (strong, nonatomic) SRHomeworkDetailItemModel *detialModel;
@property (strong, nonatomic) SRHomeworkPictureModel *currentItemModel;

@property (assign, nonatomic) CGFloat headerHeight;
@property (assign, nonatomic) BOOL isFinished;

@property (strong, nonatomic) NSString *mp3Path;
@property (strong, nonatomic) NSString *audioFileName;

@property (strong, nonatomic) UIActivityIndicatorView *activityView;


@end

@implementation SRHomewokPictureViewController

- (void)doBack {
    
    if (self.isFinishedDetail) {
        [super doBack];
        return;
    }
    
    
    if (self.isFinished) {
        [super doBack];
    } else {
        WEAKSELF
        UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"确认放弃" message:@"任务未完成，是否放弃？" cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        } otherButtonTitles:@"确定", nil];
        
        [alertView show];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
    [self setupData];
    [self setupView];
    [self setupBottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
    
//    [self showLoadingViewWithCompletedBlock:nil];
    [self startProgressHUD];
    
    if (self.isFinishedDetail) {
        self.collectionView.allowsSelection = NO;

        [self queryDataFinishDetail];
        
    } else {
        [self queryData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
//    [self updateHeaderViewHeight];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    
}

- (void)updateHeaderViewHeight {
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.headerHeight);

}

#pragma mark - setup

- (void)setupData {
    self.items = [@[] mutableCopy];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    CGFloat itemSpace = 10;
    CGFloat cellWidth = floorf((SCREEN_WIDTH - itemSpace * 3) / 2.f) - 1;
    CGFloat cellHeight = cellWidth * 110 / 172.5;
    
    flowLayout.itemSize = CGSizeMake(cellWidth, cellHeight);
    flowLayout.minimumLineSpacing = itemSpace;
    flowLayout.minimumInteritemSpacing = itemSpace;
    flowLayout.sectionInset = UIEdgeInsetsMake(itemSpace * 2, itemSpace, itemSpace, itemSpace);
    flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 320);
    
    self.flowLayout = flowLayout;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    [self.collectionView registerNib:[UINib nibWithNibName:kSRHomeworkPictureCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kSRHomeworkPictureCollectionViewCell];
    [self.collectionView registerNib:[UINib nibWithNibName:kSRHomeworkPictureCollectionHeaderView bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kSRHomeworkPictureCollectionHeaderView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
//    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view);
//    }];
    self.view.backgroundColor = self.collectionView.backgroundColor = css.color_2;
    
   
//    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"SRHomeworkPictureHeaderView" owner:nil options:nil] firstObject];
//    self.headerHeight = 386;
//    self.headerView.homeworkType = self.homeworkType;
//    
//    self.headerView.touchAudioBlock = ^{
//        [weakSelf onTouchAudioPlayButton:nil];
//    };
//    
//    self.headerView.didChangeDescHeightBlock = ^(CGFloat height) {
//        weakSelf.headerHeight = 386 + height;
//        [weakSelf updateHeaderViewHeight];
//    };
    
//    self.tableView.tableHeaderView = self.headerView;
    
          SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    [audioPlayer setAudioFilePath:nil];
    [audioPlayer setAudioFileName:nil];

        audioPlayer.audioPlayerCompletedBlock = ^(BOOL finish) {
            [weakSelf.headerView setActivityAnimated:NO];
            [weakSelf.activityView stopAnimating];
        };
        
        audioPlayer.audioPlayerProgressBlock = ^(CGFloat progress) {
            if (progress > 0.2) {
//                [weakSelf.activityView stopAnimating];
            }
            
        };
        
        audioPlayer.audioRecorderFailureBlock = ^(NSString *message) {
            [weakSelf showHUDErrorMessage:message];
        };
    
}

- (void)setupBottomView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor colorWithHex:0x4e4033];
    self.bottomView = bottomView;
    [self.view addSubview:bottomView];
    
    UIButton *preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [preButton setTitle:@"上一题" forState:UIControlStateNormal];
    preButton.titleLabel.font = css.fontOfH5;
    [preButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [preButton addTarget:self action:@selector(onPreButton:) forControlEvents:UIControlEventTouchUpInside];
    self.previousButton = preButton;
    [self.bottomView addSubview:preButton];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    nextButton.titleLabel.font = css.fontOfH5;
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(onNextButton:) forControlEvents:UIControlEventTouchUpInside];
    self.nextButton = nextButton;
    [self.bottomView addSubview:nextButton];
    
    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(60);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.top.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(60);
    }];
}


#pragma mark - Event

- (void)onPreButton:(UIButton *)sender {
    if (self.currentItemModel.index > 0 && self.currentItemModel.index < [self.detialModel.problems count] ) {
        self.currentItemModel = self.detialModel.problems[self.currentItemModel.index - 1];
        [self updateCurrentItemInfo:self.currentItemModel];
    } else {
        [self showHUDHintWithText:@"已经是第一题"];
    }
}

//- (void)onNextButton:(UIButton *)sender {
//    
//}

- (void)onTouchAudioPlayButton:(id)sender {
    SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    NSString *url = self.currentItemModel.audio;
    
    if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
        if (audioPlayer.isPlaying) {
            [self.headerView setActivityAnimated:NO];
            [audioPlayer pauseRecordAudio];
        } else {
            [self.headerView setActivityAnimated:YES];
            [audioPlayer startPlayRecordAudio];
        }
    }
    else {
        [self.headerView setActivityAnimated:YES];
        [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
        [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
        
    }
}

- (void)onNextButton:(id)sender {
    
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
        
        if (self.isFinishedDetail) {
                //完成返回；
            UIViewController *destVC = nil;
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:NSClassFromString(@"SRClassHomeWorkDetailViewController")]) {
                    destVC = vc;
                    break;
                }
            }
            
            if (destVC) {
                [self.navigationController popToViewController:destVC animated:YES];
            } else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            
            return;
        }
            //若当前是最后一题，则提交
        NSMutableDictionary *answerDict = [NSMutableDictionary dictionaryWithCapacity:4];
        for (SRHomeworkPictureModel *item in self.detialModel.problems) {
            [answerDict setValue:item.answerByUser forKey:item.problem_id];
        }
        
        if ([[answerDict allKeys] count] <= 0) {
            [self showHUDHintWithText:@"你还没有选择答案，请选择后再提交。"];
            return;
        }
        
        [self startProgressHUDWithText:@"提交中..."];
        
        self.isFinished = YES;
        
        NSError *error;
        NSString *answer = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:answerDict options:NSJSONWritingPrettyPrinted error:&error];
        if (! jsonData) {
                //转化失败
        } else {
            answer = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        
        WEAKSELF
        [SRSchoolClassServices submitProblemAnswerWithTaskID:self.taskID groupID:self.detialModel.group_id answer:answer SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                [weakSelf showHUDHintWithText:@"提交成功"];
                [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
                
            } else {
                [weakSelf showHUDHintWithText:message];
            }
        } failureBlock:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
        
    } else{
            //下一题
        if (self.currentItemModel.index < [self.detialModel.problems count]) {
            self.currentItemModel = self.detialModel.problems[self.currentItemModel.index + 1];
            
            [self updateCurrentItemInfo:self.currentItemModel];
        }
    }
}

- (void)updateCurrentItemInfo:(SRHomeworkPictureModel *)item {
    [self.headerView updateQuestionInfo:item];
    [self updatenextButtonTitle];
    
    CGFloat heightOffset = 0;
    CGFloat maxWidth = SCREEN_WIDTH - 35;
    CGSize maxSize = [item.desc textSizeWithFont:[UIFont systemFontOfSize:13.f] constrainedToSize:CGSizeMake(maxWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    if (maxSize.height < 32) {
            //小于两行，隐藏扩展按钮
        heightOffset =  0;
    } else {
        heightOffset = maxSize.height - 32;
    }
    
    self.headerHeight = 320 + heightOffset;
    self.flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, self.headerHeight);
    [self.items removeAllObjects];
    [self.items addObjectsFromArray:item.answerArray];
    
    [self.collectionView reloadData];
    
    [self performSelector:@selector(scrollToVisible) withObject:nil afterDelay:0.5];
    

    if (self.isFinishedDetail) {
            //                [self showUserRecordView];
        //选中
        
    } else {
        if (item.audio && [item.audio length] > 0) {
            [self onTouchAudioPlayButton:nil];
        }
    }
}

- (void)scrollToVisible {
    if ([self.items count] > 0){
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self.items count] - 1 inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}
    
- (void)showLoginViewController {
    [[SRLoginManager sharedManager] logout];
    [[SRLoginManager sharedManager] showLoginViewSinceController:self];
}

#pragma mark - Query Data


- (void)queryData{
        WEAKSELF
        [SRSchoolClassServices queryProblemDetailWithTaskID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
//            [weakSelf.tableView.footer endRefreshing];
    
            if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
                weakSelf.detialModel = responseDataObject;
                
                [weakSelf parseQuestionModel:weakSelf.detialModel];
            } else {
                [weakSelf showHUDErrorMessage:message];
            }
            
        } failureBlock:^(id responseObject, NSError *error) {
//            [weakSelf.tableView.footer endRefreshing];
            [weakSelf stopProgressHUD];
    
        }];
    
}

- (void)queryDataFinishDetail{
    WEAKSELF
    [SRSchoolClassServices queryProblemFinishDetailWithFinishID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
            //            [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            weakSelf.detialModel = responseDataObject;
            
            [weakSelf parseQuestionModel:weakSelf.detialModel];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
            //            [weakSelf.tableView.footer endRefreshing];
        [weakSelf stopProgressHUD];
        
    }];
    
}

- (void)parseQuestionModel:(SRHomeworkDetailItemModel *)questionModel {
    if ([questionModel.problems count] > 0) {
        for (int i = 0; i < [questionModel.problems count]; ++ i) {
            SRHomeworkPictureModel *item = questionModel.problems[i];
            
            NSMutableArray *array = [NSMutableArray array];
            NSDictionary *answerDict = item.answer_pic;
            
            [answerDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                SRHomeworkAnswerModel *answerModel = [[SRHomeworkAnswerModel alloc] init];
                answerModel.problem_id = item.problem_id;
                answerModel.key = key;
                answerModel.pic = obj;
                
                [array addObject:answerModel];
            }];
            [array sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                SRHomeworkAnswerModel *item1 = obj1;
                SRHomeworkAnswerModel *item2 = obj2;
                return [item1.key compare:item2.key options:NSCaseInsensitiveSearch];
                
            }];
            
            item.answerArray = array;
            
            item.index = i;
        }
        
        self.title = questionModel.title;
        
        self.currentItemModel = [questionModel.problems firstObject];
        [self updateCurrentItemInfo:self.currentItemModel];
    }
}

- (void)showUserRecordView {
    
//    if (self.currentItemModel.answerByUser && [self.currentItemModel.answerByUser length] > 0) {
//        NSInteger timeStamp = [self.currentItemModel.audio_timelen integerValue];
//        if (timeStamp <= 60) {
//            self.recordTimeLabel.text = [NSString stringWithFormat:@"%02lld秒", timeStamp];
//        } else {
//            self.recordTimeLabel.text = [NSString stringWithFormat:@"%02lld分%02lld秒", timeStamp / 60, timeStamp % 60];
//        }
//        [self.tableView addSubview:self.recordContentView];
//        self.recordContentView.frame = CGRectMake(SCREEN_WIDTH - 220, self.headerHeight + 30, 200, 44);
//    } else {
//        self.recordContentView.hidden = YES;
//    }
   
}

- (void)updatenextButtonTitle {
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
            //最后一个问题，
        if (self.isFinishedDetail) {
            [self.nextButton setTitle:@"完成" forState:UIControlStateNormal];
        } else {
            [self.nextButton setTitle:@"提交" forState:UIControlStateNormal];
        }
    } else {
        [self.nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SRHomeworkPictureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSRHomeworkPictureCollectionViewCell forIndexPath:indexPath];
    SRHomeworkAnswerModel *item = self.items[indexPath.row];
    cell.rightAnswer = self.currentItemModel.answer;
    [cell updateCellInfo:item];
    
    if (self.isFinishedDetail) {
        if ([self.currentItemModel.answerByUser isEqualToString:item.key]) {
            [cell setSelected:YES];
        }
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SRHomeworkPictureCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kSRHomeworkPictureCollectionHeaderView forIndexPath:indexPath];
        
        self.headerView = headerView;
        
        WEAKSELF
        self.headerView.homeworkType = self.homeworkType;
        
        self.headerView.touchAudioBlock = ^{
            [weakSelf onTouchAudioPlayButton:nil];
        };
        
        if (self.detialModel) {
            [self.headerView updateHeaderInfo:self.detialModel];
        }
        
        if (self.currentItemModel) {
            [self.headerView updateQuestionInfo:self.currentItemModel];
        }
        
       
        return headerView;
        
    }
    
    return nil;
}

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
//
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    if (self.homeworkType == SRClassHomeworkTypePicture) {
//        return [self.items count];
//    }
//    
//    return 0;
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    SRHomeworkPictureTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRHomeworkPictureTableViewCell forIndexPath:indexPath];
//
//    SRHomeworkAnswerModel *item = self.items[indexPath.row];
//    [cell updateCellInfo:item];
//    
//    if (self.isFinishedDetail) {
//        cell.isFinishDetail = YES;
//        
//        if ([item.key isEqualToString:self.currentItemModel.answerByUser]) {
////            [cell setSelected:YES];
//            cell.selectView.hidden = NO;
////            [cell.contentView bringSubviewToFront:cell.selectView];
////            cell.selectView.backgroundColor =[UIColor redColor];
//            
//        } else {
////            [cell setSelected:NO];
//            cell.selectView.hidden = YES;
//        }
//    }
//    
//
//    return cell;
//}


#pragma mark - UITableViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SRHomeworkAnswerModel *item = self.items[indexPath.row];
    self.currentItemModel.answerByUser = item.key;
    
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
        //最后一题，用户自己提交
    } else {
        [self performSelector:@selector(onNextButton:) withObject:nil afterDelay:1];
    }
    
//    if ([self.currentItemModel.answer isEqualToString:item.key]) {
//        [self showHUDHintWithText:@"太棒了，回答正确！！！" image:[UIImage imageNamed:@"right"]];
//    } else {
//        [self showHUDHintWithText:@"答错了，继续加油哦！！！" image:[UIImage imageNamed:@"worry"]];;
//    }
}

@end
